package com.example.demo.limit.guava;

import com.example.demo.limit.LimitService;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author lyc
 * @date 2019/6/11.
 * @link https://www.cnblogs.com/xuwc/p/9123078.html,https://www.cnblogs.com/softidea/p/6229543.html
 * ngnix https://blog.csdn.net/qq_28710983/article/details/80923097,https://www.cnblogs.com/devinzhang/p/7735397.html
 * https://my.oschina.net/chenxiaobian/blog/888196?tdsourcetag=s_pctim_aiomsg
 */
@Slf4j
@Service
public class RateLimiterServiceImpl implements LimitService {

    ExecutorService exec = Executors.newCachedThreadPool();// 线程池
    final RateLimiter limit = RateLimiter.create(2);//1s只能有10个

    @Override
    public void limit() {
        // 模拟20个客户端访问
        for (int index = 0; index < 20; index++) {
            final int NO = index;
            Runnable run = new Runnable() {
                public void run() {
                    try {
                        // 获取许可
                        limit.acquire();
                        //处理业务
                        log.info("Accessing: " + NO);
                        Thread.sleep((long) (Math.random() * 10000));
                    } catch (InterruptedException e) {
                        log.info("error:{}", e);
                    }
                }
            };
            exec.submit(run);
        }
    }

}